package com.xin.di.uav.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.xin.di.uav.common.enums.ServicePrefixEnum;
import com.xin.di.uav.common.exception.BusinessException;
import com.xin.di.uav.common.request.CarrierWaybillRequest;
import com.xin.di.uav.common.request.CreateWaybillRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.MediaType;
import okhttp3.Response;

import java.io.IOException;

/**
 * @author Siybom
 */
@RestController
@Slf4j
public class FyUtils {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    public String getFyToken() {
        String token = (String) redisTemplate.opsForValue().get(ServicePrefixEnum.RESCUE + RedisPrefixKey.FY_TOKEN);
        if (!ObjectUtils.isEmpty(token)) {
            return token;
        }
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n    \"appKey\": \"IE-UOCS-OUT\",\r\n    \"appSecret\": \"fykj12345678\",\r\n    \"deviceId\": \"c821554541d45deb204d94d77afc8a3f\",\r\n    \"hostName\": \"南交飞送小程序\",\r\n    \"requestId\": \"c821554541d45deb204d94d77afc8a3f\",\r\n    \"ip\": \"127.0.0.1\",\r\n    \"userId\": \"2016887083\",\r\n    \"password\": \"c821554541d45deb204d94d77afc8a3f\"\r\n}");
        Request request = new Request.Builder()
                .url("http://ie-uocs-out.sit.sf-express.com:8000/apis-auth/login/auth")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", "token=UNIT2_A2_7bcd3b2cc205e0dd501392f34abe3a291762276341254")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            JSONArray jsonArray = new JSONArray(responseData);
            System.out.println(response);
            token = jsonArray.getJSONObject(0).getJSONObject("obj").getString("token");
            redisTemplate.opsForValue().set(ServicePrefixEnum.RESCUE + RedisPrefixKey.FY_TOKEN, token);
            return token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject carrierWaybill(CarrierWaybillRequest carrierWaybillRequest) {
        String senderLat = carrierWaybillRequest.getSenderLat();
        String senderLon = carrierWaybillRequest.getSenderLon();
        senderLon = "114.7863181";
        senderLat = "30.0489132";
        String receiverLat = carrierWaybillRequest.getReceiverLat();
        String receiverLon = carrierWaybillRequest.getReceiverLon();
        receiverLat = "30.0385420";
        receiverLon = "114.7933893";
        String token = this.getFyToken();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n    \"devCode\": \"2016887083\",\r\n    \"gpsType\": 1,\r\n    \"goodsType\": \"1\",\r\n    \"goodsWeight\": \"10\",\r\n    \"senderLon\": \"" + senderLon + "\",\r\n    \"senderLat\": \"" + senderLat + "\",\r\n    \"receiverLon\": \"" + receiverLon + "\",\r\n    \"receiverLat\": \"" + receiverLat + "\"\r\n}");
        Request request = new Request.Builder()
                .url("http://ie-uocs-out.sit.sf-express.com:8000/uocs-ces/openApi/carrierWaybill")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            System.out.println(212);
            JSONObject jsonObject = JSONObject.parseObject(responseData);
            if (!jsonObject.getBoolean("success")) {
                log.warn(jsonObject.getString("errorMessage"));
                throw new BusinessException("询单失败，请联系管理员");
            }
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public String createWaybill(CreateWaybillRequest createWaybillRequest) {
        String token = this.getFyToken();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n    \"devCode\": \"2016887083\",\r\n    \"gpsType\": 1,\r\n    \"goodsType\": \"1\",\r\n    \"goodsWeight\": \"10\",\r\n    \"senderLon\": \"114.7863181\",\r\n    \"senderLat\": \"30.0489132\",\r\n    \"receiverLon\": \"114.7933893\",\r\n    \"receiverLat\": \"30.0385420\",\r\n    \"pushTime\": \"2024-10-21 17:00:00\",\r\n    \"useCab\": 1,\r\n    \"bizCode\": \"ORDER123456\",\r\n    \"senderCode\": \"" + createWaybillRequest.getSenderCode() + "\",\r\n    \"senderAddr\": \"北京市东城区长安街1号\",\r\n    \"senderTel\": \"13800138000\",\r\n    \"senderName\": \"张三\",\r\n    \"receiverCode\": \"" + createWaybillRequest.getReceiverCode() + "\",\r\n    \"receiverAddr\": \"上海市黄浦区南京东路100号\",\r\n    \"receiverTel\": \"13900139000\",\r\n    \"receiverName\": \"李四\"\r\n}");
        Request request = new Request.Builder()
                .url("http://ie-uocs-out.sit.sf-express.com:8000/uocs-ces/openApi/createWaybill")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(responseData);
            if (!jsonObject.getBoolean("success")) {
                log.warn(jsonObject.getString("errorMessage"));
                throw new BusinessException("下单失败，请联系管理员");
            }
            return jsonObject.getJSONObject("obj").getString("fyCode");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
